package ua.kharkov.khpi.tarasenko.bach.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

/**
 * Filter that check request's encoding and set it to UTF-8 if it isn't set.
 * 
 * @author oleksandr
 * 
 */
public class EncodingFilter implements Filter {
	private static final Logger log = Logger.getLogger(EncodingFilter.class);

	private String encoding;

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		HttpServletRequest httpReq = (HttpServletRequest) request;

		String requestEncoding = httpReq.getCharacterEncoding();
		if (requestEncoding == null) {
			if (log.isDebugEnabled()) {
				log.debug("Request encoding=null, set request encoding="
						+ encoding);
			}
			httpReq.setCharacterEncoding(encoding);
		}

		chain.doFilter(request, response);
	}

	public void init(FilterConfig fConfig) throws ServletException {
		if (log.isDebugEnabled()) {
			log.debug("Initialization started!");
		}

		encoding = fConfig.getInitParameter("encoding");
		if (log.isTraceEnabled()) {
			log.trace("Default encoding set to=" + encoding);
		}

		if (log.isDebugEnabled()) {
			log.debug("Initialization finished!");
		}
	}

	public void destroy() {
		if (log.isDebugEnabled()) {
			log.debug("Desrtaction started!");
		}

		// do nothing
		if (log.isDebugEnabled()) {
			log.debug("Desrtaction finished!");
		}
	}
}
